<?php
declare (strict_types = 1);
namespace app\shop\model;
use app\common\model\BaseModel;
use app\common\self\SelfRedis;
use Exception;
use think\Model;

use think\Db;

Class UserCoupon extends BaseModel
{
    // 领取优惠券
    public function userApplyCoupon($user,$param){
        $coupon_id = isset($param['coupon_id']) ? $param['coupon_id'] : 0;
        if(!$coupon_id || $coupon_id < 0) return retu_json(400,'优惠券id不得为空');
        $where = [];
        $where[] = ['id','=',$coupon_id];
        $where[] = ['apply_status','=',1];
        $where[] = ['is_delete','=',0];
        $where[] = ['end_time','>',time()];
        if(!$couponOne = ShopCoupon::where($where)->find()) return retu_json(400,'该优惠券记录不存在');
        // 优惠券状态
        if($couponOne->apply_status == 2) return retu_json('优惠券已派发完毕');
        // 优惠券
        if($couponOne->apply_status == 3) return retu_json('该优惠券商家已回收');
        // 判断是否领取过
        if($this::where(['coupon_id' => $couponOne->id])->count()) return retu_json(200,'该优惠券已领取');
        // 防止并发
        $sr = new SelfRedis();
        if($sr->redis->get('apply_coupon_'.$user->id)) return retu_json('3秒后重试');
        $sr->redis->setnx('apply_coupon_'.$user->id,1,3);
        
        // 拿取 键值
        $redis_key = 'apply_coupon_nums_'.$couponOne->id;
        $apply_nums = $sr->redis->get($redis_key);
        if($apply_nums && $apply_nums >= $couponOne->total) return retu_json('抱歉，此优惠券已经领取完毕');
        $bool = false;
        // 开始领取流程
        try{
            $this::startTrans();
            $data = [
                'uid' => $user->id,
                'coupon_id' => $couponOne->id,
                'type' => 1,
                'use_status' => $couponOne->status,
                'status' => 0,
                'total_amount' => $couponOne->total_amount,
                'amount' => $couponOne->amount,
                'add_time' => time(),
                'start_time' => $couponOne->start_time,
                'end_time' => $couponOne->end_time
            ];
            $coupon_id = $this::insertGetId($data);
            if(!$coupon_id) return retu_json(400,'网络异常，麻烦重新尝试1');
            $apply_limit = $sr->redis->inc($redis_key);
            $bool = true;
            $updateData = ['apply_num' => $apply_limit];
            // 如果相等 表示 已领取完毕  改变状态
            if($apply_limit >= $couponOne->total)$updateData['apply_status'] = 2;
            $flag = ShopCoupon::where('id',$couponOne->id)->update($updateData);
            if(!$flag)return exception('网络异常，麻烦重新尝试2');
            $this::commit();
            retu_json(200,'用户领取成功');
        }catch(Exception $e){
            $this::rollback();
            if($bool) $sr->redis->dec($redis_key);
            return retu_json(400,'网络错误，麻烦重新尝试'.$e->getMessage());
        }
    }

    // 优惠券状态更新
}